package com.chenjiaru.thread.lock;

import com.chenjiaru.thread.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;

/*
 * lock:显示锁，比较高级的锁，但是需要自己关闭，虽然高级但是并不是能替代synchronize
 * 当线程竞争资源激烈时使用此锁效率高于synchronize
 */
@Slf4j
public class LockDemo {

    private static Integer num = 0;
    private Lock lock = new ReentrantLock();

    public static void main(String[] arr) {
        LockDemo lockDemo = new LockDemo();
        new Thread(lockDemo::lock).start();
        new Thread(lockDemo::lock).start();


//        lockDemo.lock();


    }


    public void lock() {
        try {
            lock.lock();
            log.info("获取锁1...");
            lock.lock();
            log.info("获取锁2...");
            ThreadUtil.mySleep(3000);
            log.info("num={}", ++num);
        } finally {
            lock.unlock();
            lock.unlock();
            System.out.println(lock);
        }
    }

    public void nolock() {
        ThreadUtil.mySleep(500);
        log.info("num={}", ++num);
    }


}




